<template>
  <div class="process-main">
    <div class="topBox add_btn_top">
      <div class="switch-text" :style="{ color: switchTextColor }">
        {{ switchText }}
      </div>

      <el-switch
        class="screenSwitch"
        active-color="#2680D2"
        @change="openScrenn"
        v-model="screen"
      >
      </el-switch>
      <div class="line"></div>
      <el-button
        type="primary"
        size="mini"
        @click="handAdd"
        :loading="addLoading"
        ><i class="el-icon-plus"></i>添加
      </el-button>
      <el-button class="button" size="mini">
        <svg-icon class="svg-icon" icon-class="export" />导出
      </el-button>
    </div>
    <div class="boxLayout">
      <div class="sList" style="width: 100%">
        <div
          class="areaBox title_content_list"
          v-init-screen-h
          v-loading="loading"
        >
          <Empty v-if="tableData && tableData.length == 0"></Empty>

          <el-row :gutter="20" v-else>
            <el-col
              class="mb_sm"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
              :xl="6"
              v-for="(item, index) in tableData"
              :key="index"
            >
              <el-card class="box-card" shadow="hover">
                <div
                  slot="header"
                  class="flex-x flex-space"
                  @click="handNavTo(item)"
                >
                  <span class="title">{{ item.name }}</span>
                  <div class="flex-x">
                    <el-tooltip
                      v-vueClearIndex
                      class="item"
                      effect="dark"
                      content="编辑基础信息"
                      placement="top"
                    >
                      <i
                        @click.stop="handleEdit(item)"
                        style="color: #666; margin-right: 10px"
                        class="el-icon-edit"
                      ></i>
                    </el-tooltip>
                    <el-tooltip
                      v-vueClearIndex
                      class="item"
                      effect="dark"
                      content="导出变量"
                      placement="top"
                    >
                      <i
                        @click.stop="handleImport(item)"
                        style="color: #666; margin-right: 10px"
                        class="el-icon-download"
                      ></i>
                    </el-tooltip>
                    <el-tooltip
                      v-vueClearIndex
                      class="item"
                      effect="dark"
                      content="复制"
                      placement="top"
                    >
                      <i
                        @click.stop="handleCopy(item.token)"
                        style="color: #666; margin-right: 10px"
                        class="el-icon-document-copy"
                      ></i>
                    </el-tooltip>

                    <el-tooltip
                      v-vueClearIndex
                      class="item"
                      effect="dark"
                      content="删除"
                      placement="top"
                    >
                      <i
                        @click.stop="handleDel(item)"
                        style="color: #666"
                        class="el-icon-delete"
                      ></i
                    ></el-tooltip>
                  </div>
                </div>
                <div class="title_content_item" @click="handNavTo(item)">
                  <img class="img" src="@/assets/images/S_icon.png" alt="" />
                  <div class="content">
                    <div class="summary">
                      <span style="margin-right: 10px">
                        <span class="summary_title">制造单元:</span>
                        {{ item.manufactureSite || "--" }}
                      </span>
                    </div>
                    <div class="summary">
                      <span style="margin-right: 10px">
                        <span class="summary_title">负责人:</span>
                        {{ item.author }}
                      </span>
                    </div>
                    <div class="summary">
                      <span
                        ><span class="summary_title">版次:</span
                        >{{ item.version }}</span
                      >
                    </div>
                    <!-- <div class="summary">
                    
                  </div> -->
                    <div class="summary">
                      <span class="summary_title">创建日期:</span>
                      {{ item.createdDate | formatDate }}
                    </div>
                    <div class="summary">
                      <span class="summary_title">工艺:</span>
                      <span class="summary_parameter">
                        {{ item.technologyCount }}
                      </span>
                    </div>
                    <!-- <div class="summary">
                    <span class="summary_title"> 配方:</span>
                    <span class="summary_parameter">
                      {{ margeParameter(item.formulaParameter) }}
                    </span>
                  </div> -->
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
        <!-- 分页功能 -->
        <Pagination
          @pagination="pagination"
          :total="total"
          :page.sync="pageNum"
          :limit.sync="pageSize"
          :pageSizes.sync="pageSizes"
        />
      </div>
      <search-filter
        v-show="screen"
        @setFilterList="setFilterList"
        :userList="userList"
      ></search-filter>
    </div>
    <!-- <AddDialog
      :addFlag="addFlag"
      :isedit="isedit"
      :title="title"
      @closeDialog="closeDialog"
      ref="addDialogRef"
    ></AddDialog> -->
    <Dialog @sumbmit="init" :visible.sync="visible" ref="addDialogRef"></Dialog>
  </div>
</template>

<script>
import Pagination from "@/views/common/page";
import searchFilter from "../searchFilter.vue";
// import AddDialog from "./AddDialog.vue";
import {
  getTemplate,
  delTemplateToken,
  getTemplateToken,
  submitTemplate
} from "@/api/technology";
import ImgTitleContent from "@/components/ImgTitleContent";
import Empty from "@/components/Empty";
import { paginationMixins } from "@/mixin/pagination";
import { getUserList } from "@/api/userAuth";
import { SBGZ, TOKEN1, TOKEN2 } from "./constant";
import { jimuDel, jimuSave, reportCopy, excelQuery, saveDb } from "@/api/jimu";
import { GET_TEMPLATE_DATA } from "./constant";
import { generateId } from "@/utils";
import FileSaver from "file-saver";
import _ from "lodash";
import Dialog from "./Dialog.vue";
export default {
  components: { Dialog, Empty, Pagination, searchFilter, ImgTitleContent },
  mixins: [paginationMixins],
  data() {
    return {
      row: {},
      addLoading: false,
      userList: [],
      loading: false,
      title: "工艺模板",
      // pageNum: 1,
      // pageSize: 20,
      // pageSizes: [20, 50, 100, 300],
      // total: 0,
      screen: false,
      screenShow: false,
      switchTextColor: "#666666",
      switchText: "显示筛选",
      filterData: "",
      addFlag: false,
      isedit: false,
      editmetaData: {},
      editmetaData: true,
      tableData: [],
      params: {},
      visible: false,
      CfgInfo: {
        CAN: {
          Chn: 0,
          name: "CAN通道"
        },
        LIN: {
          Chn: 1,
          name: "LIN通道"
        }
      }
    };
  },
  computed: {
    margeParameter() {
      return function(item) {
        return item.map(m => m.key).join(",");
      };
    }
  },
  async mounted() {
    this.init();
    const res = await getUserList();
    const { data } = res.data;
    this.userList = data;
  },
  methods: {
    // 编辑基础信息
    handleEdit(item) {
      this.visible = true;
      this.$nextTick(async () => {
        const tokenRes = await getTemplateToken(item.token);
        this.$refs.addDialogRef.form = tokenRes.data;
      });
    },
    renderFieldList(data) {
      return data.map(item => {
        return {
          ...item,
          fieldName: item.key,
          fieldText: item.key,
          extJson: `{"required":${item.required}, "additional": [],"key": "${item.key}", "value": "${item.key}", "text": "${item.key}", "unit": "", "type": ${item.type}, "errorRange": "", "argument": "", "expression": "", "lowerLimit": "", "upperLimit": "", "defaultValue": "", "_text": "" }`
        };
      });
    },
    renderParameter(dbChName, dbCode, fieldList, apiUrl, tokenKey) {
      return {
        apiConvert: "",
        apiMethod: "0",
        // process.env.VUE_APP_BASE_URL + 此处不拼接前缀,后续在积木导入的时候二次拼接 解决不同环境的情况
        apiUrl: apiUrl,
        dbChName: dbChName, // "工艺变量",
        dbCode: dbCode, //"gybl",
        dbSource: "",
        dbType: "1",
        fieldList: fieldList,
        isList: "1",
        isPage: "1",
        jimuReportId: "",
        jsonData: "",
        // 路径上的参数
        paramList: [
          {
            extJson: "",
            id: "",
            orderNum: 1,
            paramName: tokenKey,
            paramTxt: "",
            paramValue: "",
            tableIndex: 1,
            _index: 0,
            _rowKey: 16
          }
        ]
      };
    },
    // 导出工艺参数
    handleImport(row) {
      // 配方,工艺
      const { formulaParameter, technologyParameter } = row;
      const gybl = this.renderFieldList(technologyParameter);
      // 判断是否存在阶段,不存在手动添加
      const isStage = formulaParameter.find(item => item.key === "阶段");
      if (!isStage) {
        formulaParameter.unshift({
          additional: [],
          argument: "",
          defaultValue: "",
          errorRange: "",
          expression: "",
          key: "阶段",
          lowerLimit: "",
          pos: "",
          required: false,
          text: "阶段",
          type: "0",
          unit: "",
          upperLimit: "",
          value: "阶段"
        });
      }
      const pfbl = this.renderFieldList(formulaParameter);
      const obj1 = this.renderParameter(
        "工艺变量",
        "gybl",
        gybl,
        "/technology/technology/report?token=${" + TOKEN1 + "}",
        TOKEN1
      );
      const obj2 = this.renderParameter(
        "配方变量",
        "pfbl",
        pfbl,
        "/technology/formula/report?token=${" + TOKEN2 + "}",
        TOKEN2
      );
      // 设备工装
      const obj3 = SBGZ;
      const data = JSON.stringify([obj1, obj2, obj3]);
      const blob = new Blob([data], { type: "" });
      FileSaver.saveAs(blob, row.name + "-模板参数.json");
    },
    handleCopy(token) {
      this.$confirm("是否确认复制吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          await reportCopy({ id: token, token: "undefined" });

          const excelQueryRes = await excelQuery({
            pageNo: 1,
            pageSize: 1,
            reportType: "datainfo",
            name: ""
          });
          if (!excelQueryRes.data.result.records.length) {
            this.$msg("复制失败");
            return;
          }
          const { id } = excelQueryRes.data.result.records[0];
          const tokenRes = await getTemplateToken(token);
          const name =
            tokenRes.data.name.split("副本")[0] + "副本" + generateId(4);
          await submitTemplate({
            ...tokenRes.data,
            name: name,
            id: "",
            token: id
          });
          this.$msg({
            type: "success",
            message: "复制成功!"
          });
          this.init();
        })
        .catch(err => {});
    },
    handleDel(row) {
      if (row.technologyCount) {
        this.$msg("当前模板下存在工艺,无法删除");
        return;
      }
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          await jimuDel({ id: row.token, token: undefined });
          delTemplateToken(row.token).then(res => {
            this.$msg({
              type: "success",
              message: "删除成功!"
            });
            this.init();
          });
        })
        .catch(err => {});
    },
    handNavTo(row) {
      this.$router.push({
        name: "templateDetail",
        query: {
          id: row.token,
          manufactureSite: row.manufactureSite,
          isCreate: false
        }
      });
    },
    //筛选调用
    setFilterList(data) {
      if (data) {
        this.switchTextColor = "#2680D2";
        this.switchText = "显示筛选 ( 已筛选 )";
      } else {
        this.switchTextColor = "#666666";
        this.switchText = "显示筛选";
      }
      this.filterData = data;
      this.init();
    },
    //获取模板列表
    init() {
      this.loading = true;
      this.params = {
        page: this.pageNum,
        pageSize: this.pageSize
      };
      if (this.filterData) {
        this.params = {
          ...this.params,
          ...this.filterData
        };
      }
      getTemplate(this.params)
        .then(r => {
          const { data } = r;
          this.total = data.numResults;
          this.tableData = data.results;
          this.$forceUpdate();
        })
        .finally(f => {
          this.loading = false;
        });
    },

    // pagination({ page, limit }) {
    //   this.pageNum = page;
    //   this.pageSize = limit;
    // },
    indexMethod(index) {
      return index + 1;
    },
    // 显示筛选窗
    openScrenn() {},
    // 循环添加积木默认变量
    getTree(excel_config_id) {
      const arr = GET_TEMPLATE_DATA(excel_config_id);

      return new Promise(async (resolve, reject) => {
        for (let i = 0; i < arr.length; i++) {
          await saveDb(arr[i]);
        }
        resolve();
      });
    },
    //添加
    async handAdd() {
      this.addLoading = true;
      try {
        const res = await jimuSave();
        const { id } = res.data.result;
        await this.getTree(id);
        this.addLoading = false;
        this.$router.push({
          name: "templateDetail",
          query: {
            id,
            isCreate: true
          }
        });
      } catch (error) {
        this.$msg("添加失败");
        this.addLoading = false;
      }
    },
    closeDialog(isRefresh) {
      // isRefresh是否刷新
      if (isRefresh) {
        this.getTemplateList();
      }
      this.addFlag = false;
      this.isedit = false;
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/assets/style/processCss/baseStyle.css";
@import "~@/styles/mixin.scss";
/* .boxLayout {
  display: flex;
} */
.summary_parameter {
  color: #2680d2;
  text-decoration: underline;
}
.title_content_list {
  .title {
    color: #333;
    font-size: 16px;
    @include textoverflow(1);
  }
  /deep/ .el-card__header {
    padding: 10px;
  }
}
.title_content_item {
  display: flex;
  align-items: center;

  padding: 16px;
  .del_icon {
    display: none;
  }
  &:hover {
    .del_icon {
      display: block;
    }
  }
  .content {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    width: 100%;

    .summary {
      color: #999999;
      font-size: 12px;
      margin-top: 6px;
      @include textoverflow(1);
      .summary_title {
        color: #666;
      }
    }
  }

  .img {
    width: 66px;
    /* height: 100px; */
    min-width: 66px;
    margin-right: 14px;
  }
}
.sList {
  background-color: #fff;
  padding: 20px;
  padding-bottom: 0;
  /* padding-bottom: 20px; */
}
</style>
